package com.theorydance.esoperator.utils;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Author grand_ranfs
 * @Date 2024/6/13  8:42
 */
public class ByteArrayVisualizer {

    /**
     *可视化输出byte[]内容，按16位（即每两个字节）一行打印到控制台。
     * @param byteArray 要可视化的byte数组
     */
    public static void visualizeByteArray(byte[] byteArray) {
        if (byteArray == null || byteArray.length == 0) {
            System.out.println("Byte array is null or empty.");
            return;
        }
        System.out.println("         +-------------------------------------------------+");
        System.out.println("         | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F |");
        System.out.println("+--------+-------------------------------------------------+------------------+");
        for (int i = 0; i < byteArray.length; i += 16) {
            // 打印地址
            System.out.printf("|%08x| ", i);

            // 每行打印16个字节
            for (int j = 0; j < 16 && (i + j) < byteArray.length; j++) {
                // 打印当前字节的十六进制表示，不足两位前面补0
                System.out.printf("%02x ", byteArray[i + j]);
            }

            // 填充空格，使得每行长度一致，直到达到16个字节的显示宽度
            if (byteArray.length < i + 16) {
                for (int j = (i + 16) - byteArray.length; j > 0; j--) {
                    System.out.print("   ");
                }
            }

            System.out.print("| ");

            // 打印ASCII部分
            for (int j = 0; j < 16 && (i + j) < byteArray.length; j++) {
                // 只打印ASCII范围内的字符（32-126）
                char c = (char) (byteArray[i + j] & 0xFF);
                if (c >= 32 && c <= 126) {
                    System.out.print(c);
                } else {
                    System.out.print(".");
                }
            }
            if (i + 16 >= byteArray.length) {
                for(int j = 0;j < (16 - byteArray.length%16)%16;j++) {
                    System.out.print(" ");
                }
            }
            System.out.println(" |");
        }
        System.out.println("+--------+-------------------------------------------------+ length = " + byteArray.length);
    }

    public static void main(String[] args) throws Exception{
        String obj = "你好";
        byte[] bytes1 = obj.getBytes(StandardCharsets.UTF_8);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(obj);
        byte[] bytes2 = byteArrayOutputStream.toByteArray();


        visualizeByteArray(bytes1);
        visualizeByteArray(bytes2);
    }
}

